<template>
	<a-modal
		:visible="visible"
		width="500px"
		:title="(props.data.id ? '编辑' : '添加') + '同住人'"
		centered
		destroyOnClose
		@cancel="cancel"
		:footer="null"
		:maskClosable="false"
		:bodyStyle="{padding: 0}">
		<a-form ref="formRef" :model="modelRef" class="flex-container-nomal" @finish="run" :labelCol="{style: {width: '90px'}}">
			<div class="flex1 auto-y">
				<a-form-item label="姓名" name="name" :rules="[{required: true, message: '请输入姓名'}]">
					<a-input-group compact>
						<a-input v-model:value="modelRef.name" placeholder="请输入姓名" style="width: calc(100% - 91px)" />
						<a-form-item-rest>
							<a-radio-group v-model:value="modelRef.gender" button-style="solid">
								<a-radio-button :value="1">男</a-radio-button>
								<a-radio-button :value="2">女</a-radio-button>
							</a-radio-group>
						</a-form-item-rest>
					</a-input-group>
				</a-form-item>
				<a-form-item label="电话" name="phone" :rules="rules.phone">
					<a-input v-model:value="modelRef.phone" :maxlength="11" placeholder="请输入电话" />
				</a-form-item>
				<a-form-item label="身份信息" name="identityCard" :rules="identityCard">
					<a-input-group compact>
						<a-form-item-rest>
							<a-select
								v-model:value="modelRef.certificationType"
								:options="certificateOptions"
								placeholder="请选择证件类型"
								@change="formRef.resetFields('identityCard')"
								style="width: 35%" />
						</a-form-item-rest>
						<a-input v-model:value="modelRef.identityCard" :maxlength="18" placeholder="请输入证件号码" style="width: 65%" />
					</a-input-group>
				</a-form-item>
				<a-form-item label="关系" name="renterRelation" :rules="[{required: true, message: '请选择关系'}]">
					<a-select v-model:value="modelRef.renterRelation" :options="renterRelationList" placeholder="请选择关系" />
				</a-form-item>
				<a-form-item label="附件" name="frontImgUrl" :rules="[{required: frontImgUrl, message: '请上传证件照片'}]">
					<a-button type="link" size="small" @click="visibles.certificate = true">
						上传证件照片
						<template v-if="modelRef.frontImgUrl || modelRef.rearImgUrl">
							<check-outlined />
						</template>
						<plus-outlined v-else />
					</a-button>
				</a-form-item>
			</div>
			<div class="a-modal-dialog-footer">
				<a-space :size="12">
					<a-button @click="cancel">取消</a-button>
					<a-button type="primary" html-type="submit" :loading="loading" :disabled="loading">确定</a-button>
				</a-space>
			</div>
		</a-form>
	</a-modal>
	<certificate-upload-dialog v-model:visible="visibles.certificate" :imgs="modelRef" />
</template>
<script setup lang="ts">
	import {reactive, ref, watch} from 'vue'
	import {useRequest} from 'vue-request'
	import {editRoommate, roommateSave} from '@/api/contract'
	import type {Rule} from 'ant-design-vue/es/form'
	import {CheckOutlined, PlusOutlined} from '@ant-design/icons-vue'
	import {rules} from '@/utils/rules'
	import {renterRelationList} from '@/utils'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import {checkIdCard} from '@/utils/check'
	import CertificateUploadDialog from '@/components/common/certificate-upload-dialog.vue'
	import settingApi from 'yuxin-base/src/api/setting-api'
	const modelRef = reactive<any>({
		name: null,
		gender: 1,
		phone: null,
		identityCard: null,
		nationality: null,
		certificationType: 1,
		renterRelation: null,
		// 身份证正面
		frontImgUrl: null,
		// 身份证反面
		rearImgUrl: null
	})

	const props = withDefaults(
		defineProps<{
			visible?: boolean
			contractId?: [string, number]
			data?: object
		}>(),
		{
			visible: false
		}
	)

	const visibles = reactive({
		certificate: false
	})

	const certificateOptions = Object.keys(CERTIFICATION_TYPE_MAP).map((key: string) => ({
		label: CERTIFICATION_TYPE_MAP[key],
		value: Number(key)
	}))
	const frontImgUrl = ref<boolean>(false)
	/** 获取决策合同设置 */
	const getContractDecision = () => {
		settingApi.getDecisionList({bizPoint: 'CONTRACT_FIELD_MUST', module: 'CONTRACT'}).then(res => {
			let source = JSON.parse(res.data[0]?.value || '[]')
			frontImgUrl.value = source.includes(3) ? true : false
		})
	}

	const identityCard = [
		{
			required: true,
			validator: async (_rule: Rule, value: string, callback: any) => {
				if (value) {
					if (modelRef.certificationType == 1 && !checkIdCard(value)) {
						return Promise.reject('证件号码格式不正确')
					} else {
						return Promise.resolve()
					}
				} else {
					return Promise.reject('请输入证件号码')
				}
			}
		}
	]

	const emit = defineEmits(['update:visible', 'success'])
	const cancel = () => {
		emit('update:visible', false)
		resetForm()
	}

	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				getContractDecision()
				Object.assign(modelRef, props.data)
			}
		}
	)

	const sendRequest = () => {
		if (props?.data?.id) {
			return editRoommate({id: props.data?.id, ...modelRef})
		} else {
			return roommateSave({contractId: props.contractId, ...modelRef})
		}
	}

	const {run, loading} = useRequest(sendRequest, {
		manual: true,
		formatResult: (res: any) => {
			if (res.code == 200) {
				// message.success('操作成功')
				setTimeout(() => {
					emit('success', res.data)
					cancel()
				}, 300)
			}
		}
	})
	// 重置表单
	const formRef = ref<any>()
	const resetForm = () => {
		Object.keys(modelRef).forEach(key => {
			if (key === 'gender' || key === 'certificationType') {
				modelRef[key] = 1
			} else {
				modelRef[key] = null
			}
		})
	}
</script>
<style lang="less"></style>
